import axios from "axios";
import store from "store";
import router from "@/router/index";
import { FINGERPRINT_LOCAL_NAME } from "@/store/modules/login";
window.router = router;
export const baseURL = import.meta.env.VITE_BASE_URL;
const request = axios.create({
  timeout: 10000,
  baseURL: `${baseURL}`,
});
request.interceptors.request.use((config) => {
  const token = store.get("token");
  if (token) {
    config.headers["Authorization"] = "Bearer " + token;
  }
  const fingerprintId = store.get(FINGERPRINT_LOCAL_NAME);

  const withCredentials = config.withCredentials == void 0 || config.withCredentials ? true : false;

  if (fingerprintId && withCredentials) {
    config.headers["fingerprintId"] = fingerprintId;
  }

  return config;
});

const ignoreErrorMsgPath = ["^/start/lyric/lyric/*"];
request.interceptors.response.use((response) => {
  if (response.data && response.data.code == 500) {
    let isMessage = true;
    for (let i = 0; i < ignoreErrorMsgPath.length; i++) {
      const path = ignoreErrorMsgPath[i];
      const reg = new RegExp(path);
      isMessage = !reg.test(response.config.url);
      if (!isMessage) break;
    }
    isMessage && Qmsg.error(response.data.msg);
    return Promise.reject(response.data);
  }

  if (response.data && response.data.code === 401) {
    Qmsg.error("登录过期，请重新登录！");
    store.remove("token");
    router.push({
      name: "Login",
      query: {
        redirect: router.currentRoute.value.path,
      },
    });
    return Promise.reject(response.data);
  }

  return response.data;
});

export default request;
